#!/bin/bash

# Disable SC2086 as it confuses the docker command.
# shellcheck disable=SC2086

# Small script to run tests for a target (or all targets) inside all the
# respective docker images.

set -eux

target="$1"

# Default to assuming the CARGO_HOME is one directory up (to account for a `bin`
# subdir) from where the `cargo` binary in `$PATH` lives.
default_cargo_home="$(dirname "$(dirname "$(command -v cargo)")")"
# If the CARGO_HOME env var is already set, use that. If it isn't set use the
# default.
export CARGO_HOME="${CARGO_HOME:-$default_cargo_home}"

echo "${HOME}"
pwd

# Avoid "no space left on device" failure if running in CI
if [ "${CI:-0}" != "0" ] && [ "$target" = "aarch64-linux-android" ]; then
    docker system prune -af
    docker system df
fi

run() {
    run_target="$1"
    echo "Building docker container for target $run_target"

    build_args=(
        "--tag=libc-$run_target"
        "--file=ci/docker/$run_target/Dockerfile"
        "ci/"
    )

    if [[ "$run_target" = *"musl"* ]]; then
        if [ -n "${RUST_LIBC_UNSTABLE_MUSL_V1_2_3:-}" ]; then
            build_args+=("--build-arg=MUSL_VERSION=new")
        else
            build_args+=("--build-arg=MUSL_VERSION=old")
        fi
    fi

    # use -f so we can use ci/ as build context
    docker build "${build_args[@]}"

    mkdir -p target
    if [ -w /dev/kvm ]; then
        kvm="--volume /dev/kvm:/dev/kvm"
    else
        kvm=""
    fi

    docker run \
        --rm \
        --user "$(id -u)":"$(id -g)" \
        --env LIBC_CI \
        --env LIBC_CI_ZBUILD_STD \
        --env RUSTFLAGS \
        --env RUSTDOCFLAGS \
        --env RUST_BACKTRACE \
        --env RUST_LIBC_UNSTABLE_GNU_FILE_OFFSET_BITS \
        --env RUST_LIBC_UNSTABLE_GNU_TIME_BITS \
        --env RUST_LIBC_UNSTABLE_MUSL_V1_2_3 \
        --env CARGO_TERM_COLOR \
        --env CARGO_TERM_VERBOSE \
        --env CARGO_HOME=/cargo \
        --env CARGO_TARGET_DIR=/checkout/target \
        --volume "$CARGO_HOME":/cargo:Z \
        --volume "$(rustc --print sysroot)":/rust:ro,Z \
        --volume "$PWD":/checkout:ro,Z \
        --volume "$PWD"/target:/checkout/target \
        $kvm \
        --init \
        --workdir /checkout \
        "libc-$target" \
        sh -c "HOME=/tmp PATH=\$PATH:/rust/bin exec ci/run.sh $target"
}

if [ -z "$target" ]; then
    # Run all docker targets
    for d in ci/docker/*; do
        run "${d}"
    done
else
    run "$target"
fi
